package self.hoy.demo.grainmall.search.service.impl;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import self.hoy.demo.common.to.es.SpuEsModel;
import self.hoy.demo.grainmall.search.config.GrainElasticSearchConfiguration;
import self.hoy.demo.grainmall.search.service.ProductService;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hyh
 * @date 2020/7/19
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 搜索引擎中索引库的名称
     */
    @Value("${search.index.product:grain_product}")
    private String index;

    @Override
    public boolean productStatusUp(List<SpuEsModel> models) throws IOException {
        // 由程序外部给ES建立映射关系，由 kibana 处理
        // 批量保存所有SKU数据
        BulkRequest request = new BulkRequest();
        for (SpuEsModel model : models) {
            //批量构造elasticsearch的请求参数
            IndexRequest req = new IndexRequest(index);
//            IndexRequest req = new IndexRequest(ElasticSearchConstant.PRODUCT_INDEX);
            req.id(model.getSkuId().toString());
            String s = JSON.toJSONString(model);
            req.source(s, XContentType.JSON);
            request.add(req);
        }
        BulkResponse bulk = restHighLevelClient.bulk(
                request,
                GrainElasticSearchConfiguration.COMMON_OPTIONS
        );
        boolean hasFailures = bulk.hasFailures();
        if (hasFailures) {
            log.error("推送商品到ElasticSearch失败", Arrays.asList(bulk.getItems()).stream().map(item->{
                return item.getId();
            }).collect(Collectors.toList()));
        }
        return !hasFailures;
    }
}
